package com.example.demo.handler;

import com.example.demo.entity.SecuritiesNews;
import com.example.demo.service.ISecuritiesNews;
import com.example.demo.vo.SecuritiesNewsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

public class StockNewsHandler extends TextWebSocketHandler {

    private final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ISecuritiesNews securitiesNews;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        // 发送历史数据
        sendHistoricalData(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 处理客户端消息，例如确认收到消息
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
    }

    // 发送历史数据给新连接的客户端
    private void sendHistoricalData(WebSocketSession session) throws IOException {
        // 获取最近的20条历史数据
        List<SecuritiesNewsVo> newsList = securitiesNews.selectSecuritiesNewsList();
        NewsResponse response = new NewsResponse("historical", newsList);
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    // 向所有客户端推送增量数据
    public void pushIncrementalData(SecuritiesNews news) {
        NewsResponse response = new NewsResponse("incremental", news);
        String jsonMessage = null;
        try {
            jsonMessage = objectMapper.writeValueAsString(response);
        } catch (JsonProcessingException e) {
            System.out.println("序列化证券新闻失败");
            return;
        }
        
        for (WebSocketSession session : sessions) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(jsonMessage));
                }
            } catch (IOException e) {
                System.out.println("发送消息失败");
            }
        }
    }
    
    // 消息响应类
    private static class NewsResponse {
        private final String type;
        private final Object data;

        public NewsResponse(String type, Object data) {
            this.type = type;
            this.data = data;
        }

        // getters
        public String getType() { return type; }
        public Object getData() { return data; }
    }
}